package com.learn.config;

import com.learn.controller.UserController;
import com.learn.entity.User;
import com.learn.entity.UserExample;
import com.learn.mybatis.mapper.UserMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserMapper userMapper;

    //    授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        为登录用户添加权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();//拿到user对象
        //设置当前用户的角色
        info.addRole(currentUser.getRole());
        return info;
    }

    //    认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //    token是封装好的用户提交的用户名密码
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(userToken.getUsername());
        List<User> users = userMapper.selectByExample(userExample);
//        用户名认证
        if (users.get(0) == null) {
            return null;
        }
//        密码认证
        return new SimpleAuthenticationInfo(users.get(0), users.get(0).getPassword(), getName());

    }
}
